﻿using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Hardware;
using FlashLightLib;

namespace FlashLight
{
	[Activity (Label = "FlashLight", MainLauncher = true, Icon = "@drawable/lightbulb")]
	public class MainActivity : Activity
	{
        private HWFlash _light = null;
        private ImageButton button = null;

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
            SetContentView (Resource.Layout.Main);
            button = FindViewById<ImageButton> (Resource.Id.btnTurn);
            button.SetImageResource(Resource.Drawable.FlashOn);
            button.Click += new EventHandler(ChangeFlashState);
		}

        protected override void OnPause()
        {
            base.OnPause();

            CloseFlash();
        }

        protected override void OnStop(){
            base.OnStop();

            CloseFlash();
        }

        protected override void OnResume()
        {
            base.OnResume();

            try
            {
                if(_light==null)
                {
                    _light = new HWFlash(this.Application);
                    _light.OnFlashChangeState += new OnFlashChangeStateHandler(OnFlashStateChanged);
                }
                _light.Init();
                _light.TurnOn();
            }
            catch(Exception ex)
            {
                TextView tv = FindViewById<TextView> (Resource.Id.textView1);
                tv.Text = ex.Message;
            }


        }

        void OnFlashStateChanged(bool state){
            if (state)
                button.SetImageResource(Resource.Drawable.FlashOff);
            else
                button.SetImageResource(Resource.Drawable.FlashOn);
        }

        void ChangeFlashState(object sender, EventArgs e)
        {
            try{
                if (_light.IsOn)
                    _light.TurnOff();
                else
                    _light.TurnOn();
            }
            catch(Exception ex)
            {
                TextView tv = FindViewById<TextView> (Resource.Id.textView1);
                tv.Text = ex.Message;
            }
        }

        void CloseFlash(){
            if (_light != null)
            {
                _light.TurnOff();
                _light.Close();
                _light = null;
            }
        }
	}



	


}


